package com.tenglong.teacher.ui.homeworkNew;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.cuotibao.zhuoxiao.basics.BaseFragment;
import com.cuotibao.zhuoxiao.basics.GlobalConstant;
import com.cuotibao.zhuoxiao.basics.utils.ToastUtils;
import com.cuotibao.zhuoxiao.basics.utils.Utils;
import com.cuotibao.zhuoxiao.basics.utils.recyview.DividerSpaceItemDecoration;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.tenglong.teacher.R;
import com.tenglong.teacher.data.resultInfo.BaseHomeWorkInfo;
import com.tenglong.teacher.data.resultInfo.CurrentHomeWorkOutsideInfo;
import com.tenglong.teacher.data.resultInfo.HistoryHomeWorkOutsideInfo;
import com.tenglong.teacher.data.resultInfo.base.BaseResult;
import com.tenglong.teacher.data.resultInfo.base.ResultVerifier;
import com.tenglong.teacher.services.WebRestApi;
import com.tenglong.teacher.services.hdx.CreateRequestEntity;
import com.tenglong.teacher.ui.port.MainCallback;
import com.tenglong.teacher.ui.port.MainFragmentRubsh;
import com.tenglong.teacher.ui.adapter.HomeWorkAdapter;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * A simple {@link Fragment} subclass.
 */
public class CurrentHomeWorkFragment extends BaseFragment implements HomeWorkAdapter.HomeworkListener, MainFragmentRubsh, OnRefreshListener {

    public static final String KEY_HOMEWORK_ID = "key_homework_id";
    public static final String KEY_CLASS_ID = "key_class_id";
    public static final String KEY_CLASS_NAME = "key_class_name";
    public static final String KEY_HOMEWORK_TAG = CurrentHomeWorkFragment.class.getCanonicalName() + "key_homework";
    private RecyclerView mRecyclerView;
    private List<BaseHomeWorkInfo> infos;
    private HomeWorkAdapter mAdapter;
    private String tag;
    private boolean isLoadWindow = false;
    private View noData;
    private SmartRefreshLayout mSmartRefreshLayout;
    private int mClickItemPosition = -1;

    public static CurrentHomeWorkFragment getInstanses(String tag) {
        CurrentHomeWorkFragment f = new CurrentHomeWorkFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_HOMEWORK_TAG, tag);
        f.setArguments(bundle);
        return f;
    }

    public CurrentHomeWorkFragment() {
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        tag = getArguments().getString(KEY_HOMEWORK_TAG);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_current_home_work, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
        initRecy();
        setAdapter();
        setListeners();
        requestData();
        isLoadWindow = true;
    }


    private void setListeners() {
        mAdapter.setHomeworkListener(this);
        mSmartRefreshLayout.setEnableLoadMore(false);
        mSmartRefreshLayout.setOnRefreshListener(this);
    }


    private void requestData() {
        if (isFirstDownLoad && !tag.equals(HomeWorkFragment.CURRENT_HOMEWORK_TAG)) {
            showProgressDialog("数据加载中...");
            isFirstDownLoad = false;
        }
        WebRestApi service = CreateRequestEntity.getWebService();
        if (tag.equals(HomeWorkFragment.CURRENT_HOMEWORK_TAG)) {
            currentHomework(service);
//            historyHomework(service);
//            mAdapter.setOld(false);
        } else {
            mAdapter.setOld(true);
            historyHomework(service);
        }
    }

    private void historyHomework(WebRestApi service) {
        service.getHistoryHomeworkOutsideData().enqueue(new Callback<BaseResult<List<HistoryHomeWorkOutsideInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<HistoryHomeWorkOutsideInfo>>> call, Response<BaseResult<List<HistoryHomeWorkOutsideInfo>>> response) {
                synchronized (CurrentHomeWorkFragment.this) {
                    mSmartRefreshLayout.finishRefresh(true);
                    if (ResultVerifier.isSucceed(response)) {
                        infos.clear();
                        infos.addAll(response.body().data);
                        mAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                    }
                    noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                    dismissProgressDialog();
                }
            }

            @Override
            public void onFailure(Call<BaseResult<List<HistoryHomeWorkOutsideInfo>>> call, Throwable t) {
                synchronized (CurrentHomeWorkFragment.this) {
                    mSmartRefreshLayout.finishRefresh(false);
                    ResultVerifier.systerErrers(t);
                    noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                    dismissProgressDialog();
                }
            }
        });
    }

    private void currentHomework(WebRestApi service) {
        service.findHwPublishByuserId().enqueue(new Callback<BaseResult<List<CurrentHomeWorkOutsideInfo>>>() {
            @Override
            public void onResponse(Call<BaseResult<List<CurrentHomeWorkOutsideInfo>>> call, Response<BaseResult<List<CurrentHomeWorkOutsideInfo>>> response) {
                synchronized (CurrentHomeWorkFragment.this) {
                    mSmartRefreshLayout.finishRefresh(true);
                    if (ResultVerifier.isSucceed(response)) {
                        infos.clear();
                        infos.addAll(response.body().data);
                        mAdapter.notifyDataSetChanged();
                    } else {
                        ToastUtils.showCenterToast(ResultVerifier.serceErrers(response));
                    }
                    noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                    dismissProgressDialog();
                }
            }

            @Override
            public void onFailure(Call<BaseResult<List<CurrentHomeWorkOutsideInfo>>> call, Throwable t) {
                synchronized (CurrentHomeWorkFragment.this) {
                    mSmartRefreshLayout.finishRefresh(false);
                    ResultVerifier.systerErrers(t);
                    noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                    dismissProgressDialog();
                }
            }
        });
    }

    private void setAdapter() {
        infos = new ArrayList<>();
        mAdapter = new HomeWorkAdapter(infos);
        mRecyclerView.setAdapter(mAdapter);
    }

    private void initRecy() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.addItemDecoration(tag.equals(HomeWorkFragment.CURRENT_HOMEWORK_TAG) ? new
                DividerSpaceItemDecoration(Utils.dip2px(mContext, 15)) : new DividerSpaceItemDecoration(Utils.dip2px(mContext, 15), Utils.dip2px(mContext, 15)));
    }

    private void initView(View view) {
        mRecyclerView = view.findViewById(R.id.mRecyclerView);
        noData = view.findViewById(R.id.noData);
        mSmartRefreshLayout = view.findViewById(R.id.smartRefreshLayout);
        mRecyclerView.setHasFixedSize(true);
        ClassicsHeader headerView = new ClassicsHeader(getContext());
        ClassicsFooter footView = new ClassicsFooter(getContext());
        headerView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        footView.setBackgroundColor(Color.parseColor("#f8f8f8"));
        mSmartRefreshLayout.setRefreshHeader(headerView);
        mSmartRefreshLayout.setRefreshFooter(footView);
    }

    @Override
    public void onClickCurrentItemListener(int position) {
        if (position == -1) return;
        this.mClickItemPosition = position;
        ((MainCallback) mContext).onHomeworkRedPoint(false);
        //此处是当前作业点击回调
        CurrentHomeWorkOutsideInfo info = (CurrentHomeWorkOutsideInfo) infos.get(position);
        Intent intent = new Intent(mContext.getApplicationContext(), HomeworkStudentListActivity.class);
        intent.putExtra(KEY_CLASS_NAME, info.className);
        intent.putExtra(KEY_HOMEWORK_ID, info.homeworkid);
        intent.putExtra(KEY_CLASS_ID, info.toClasses);
        intent.putExtra(HomeworkStudentListActivity.KEY_CLASS_TOTAL_STUDENT_NUMBER, info.stuNum);
        startActivityForResult(intent, GlobalConstant.REQUEST_CODE_HOMEWORK_STUDENT_LIST_ACTIVITY);
    }

    @Override
    public void onClickHistoryItemListener(int position) {
        if (position == -1) return;
        this.mClickItemPosition = position;
        ((MainCallback) mContext).onHomeworkRedPoint(false);
        Intent i = new Intent();
        i.putExtra("tag",tag);
        i.setClass(mContext, HomeworkClassHourActivity.class);
        i.putExtra(HomeworkClassHourActivity.KEY_CLASS_DATA, (HistoryHomeWorkOutsideInfo) infos.get(position));
        startActivity(i);
    }

    @Override
    public void onClickHistoryClassHourItemListener(int position) {
        this.mClickItemPosition = position;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case GlobalConstant.REQUEST_CODE_HOMEWORK_STUDENT_LIST_ACTIVITY:
                    if (mAdapter != null && infos != null && mClickItemPosition != -1 && infos.size() > mClickItemPosition) {
                        infos.remove(mClickItemPosition);
                        mAdapter.notifyItemRemoved(mClickItemPosition);
                        noData.setVisibility(infos.size() == 0 ? View.VISIBLE : View.GONE);
                        mClickItemPosition = -1;
                    }
                    break;
            }
        }
    }

    @Override
    public void refresh() {
        if (isLoadWindow && isAdded()) {
            requestData();
        }
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        requestData();
    }
}
